package de.mssp.sensorkit.bluetooth;

import de.mssp.sensorkit.R;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MessageActivity extends Activity {
	
	EditText mEditTextOut;
	Button mSendButton;	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.message);
		
		// Set result CANCELED in case the user backs out
        setResult(Activity.RESULT_CANCELED);
		
		mEditTextOut = (EditText)findViewById(R.id.edit_text_out);
		mEditTextOut.setOnEditorActionListener(mWriteListener);
		mSendButton = (Button)findViewById(R.id.button_send);
		mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                sendMessage(message);
            }
        });
		
		
	}
	
	// The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            return true;
        }
    };
    
    /** Send the message by returning the values from our EditText back to the BluetoothActivity */
    private void sendMessage(String msg){
    	BluetoothDevice selectedDevice = (BluetoothDevice) getIntent().getExtras().get("device");
    	Intent intent = new Intent();
        intent.putExtra("message", msg);
        intent.putExtra("device", selectedDevice);

        // Set result and finish this Activity
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

}
